package com.zhongpengcheng.fortune.es.config;

import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;

import java.nio.charset.StandardCharsets;
import java.util.ArrayList;

import static com.alibaba.fastjson.serializer.SerializerFeature.*;

/**
 * Fastjson配置
 *
 * @author zhongpengcheng
 * @date 2021-10-01 19:53:27
 **/
@ConditionalOnClass(FastJsonHttpMessageConverter.class)
@Configuration
public class FastjsonConfiguration {
    @Bean
    @SuppressWarnings("deprecation")
    public FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig config = new FastJsonConfig();
        // 设置日期格式化格式
        config.setDateFormat("yyyy-MM-dd HH:mm:ss");
        // 默认编码
        config.setCharset(StandardCharsets.UTF_8);
        // 格式化特性
        config.setSerializerFeatures(getSerializerFeatures());
        // 消息转换器默认response content-type
        converter.setSupportedMediaTypes(ListUtil.of(MediaType.APPLICATION_JSON_UTF8));
        converter.setFastJsonConfig(config);

        return converter;
    }

    /**
     * 构造fastjson的序列化特性
     * @return 注入的序列化特性
     */
    private SerializerFeature[] getSerializerFeatures() {
        ArrayList<SerializerFeature> features = new ArrayList<>();
        // 输出map中value为null的数据
        features.add(WriteMapNullValue);
        // 输出空list为[]，而不是null
        features.add(WriteNullListAsEmpty);
        // 输出空string为""，而不是null
        features.add(WriteNullStringAsEmpty);
        // 使用toString方法序列化枚举
        features.add(WriteEnumUsingToString);
        // 启用美观格式化（会占用更多空间）
        features.add(PrettyFormat);

        return ArrayUtil.toArray(features, SerializerFeature.class);
    }
}
